<template>
  <BaseWrap v-loading="isRequesting">
    <!-- 功能按钮 -->
    <div class="button-area">
      <div class="left">
        <!-- 时间 -->
        <el-date-picker
          v-model="createTime"
          :default-time="['00:00:00', '23:59:59']"
          :end-placeholder="$t('Issue.endTime')"
          :picker-options="pickerOptions"
          :range-separator="$t('Issue.to')"
          size="small"
          :start-placeholder="$t('Issue.startTime')"
          style="width:400px"
          type="daterange"
          unlink-panels
          value-format="yyyy-MM-dd HH:mm:ss"
        ></el-date-picker>
        <!-- 查询 -->
        <el-button
          class="search"
          icon="el-icon-search"
          size="mini"
          type="primary"
          @click="query"
        ></el-button>
        <!-- 导出 -->
        <el-button
          v-if="$hasPer('exportByCommodity')"
          class="export"
          icon="el-icon-download"
          size="mini"
          type="success"
          @click="exportFile"
        >
          {{ $t('button.export') }}
        </el-button>
      </div>
      <el-radio-group v-model="modelVal" size="mini">
        <el-radio-button :label="$t('Issue.panelModel')"></el-radio-button>
        <el-radio-button :label="$t('Issue.tableModel')"></el-radio-button>
      </el-radio-group>
    </div>

    <!-- 分割线 -->
    <div class="line"></div>

    <!-- 查询条件 -->
    <div class="query-area">
      <!-- 问题类型 -->
      <el-select
        v-model="queryForm.issueType"
        clearable
        :placeholder="$t('Issue.issueType')"
        size="mini"
        style="width:120px"
      >
        <el-option
          v-for="item in $store.getters['dict/dictOptions']('IssueType')"
          :key="item.code"
          :label="item.value"
          :value="item.code"
        />
      </el-select>
      <!-- 问题状态 -->
      <el-select
        v-model="queryForm.issueStatus"
        clearable
        :placeholder="$t('Issue.issueStatus')"
        size="mini"
        style="width:120px"
      >
        <el-option
          v-for="item in $store.getters['dict/dictOptions']('IssueStatus')"
          :key="item.code"
          :label="item.value"
          :value="item.code"
        />
      </el-select>
      <!-- 问题优先级 -->
      <el-select
        v-model="queryForm.issueLevel"
        clearable
        :placeholder="$t('Issue.issueLevel')"
        size="mini"
        style="width:120px"
      >
        <el-option
          v-for="item in $store.getters['dict/dictOptions']('IssueLevel')"
          :key="item.code"
          :label="item.value"
          :value="item.code"
        />
      </el-select>
      <!-- 问题创建人 -->
      <el-select
        v-model="queryForm.issueCreateUser"
        clearable
        filterable
        :placeholder="$t('Issue.issueCreateUser')"
        size="mini"
        style="width:120px"
      >
        <el-option
          v-for="item in $store.getters['user/getUserSimpleCollects']"
          :key="item.userId"
          :label="item.userName"
          :value="item.userId"
        >
          <span style="float: left;">{{ item.userName }}</span>
          <span style="float: right; color: #b4b4b4; font-size: 12px">
            {{ item.team }}
          </span>
        </el-option>
      </el-select>

      <!-- 问题负责人 -->
      <el-select
        v-model="queryForm.issueAppointUser"
        clearable
        filterable
        :placeholder="$t('Issue.issueAppointUser')"
        size="mini"
        style="width:120px"
      >
        <el-option
          v-for="item in $store.getters['user/getUserSimpleCollects']"
          :key="item.userId"
          :label="item.userName"
          :value="item.userId"
        >
          <span style="float: left;">{{ item.userName }}</span>
          <span style="float: right; color: #b4b4b4; font-size: 12px">
            {{ item.team }}
          </span>
        </el-option>
      </el-select>

      <!-- 总计 -->
      <div class="total">总计{{ filterData.length }}条</div>
    </div>

    <!-- 列表区域 -->
    <div class="list-area">
      <TableList v-if="modelVal === $t('Issue.tableModel')" :tableData="filterData" />
      <PanelList v-else :tableData="filterData" />
    </div>

    <!-- 详情 -->
    <BaseDrawer :visible.sync="detailVisible">
      <IssueDetail :richTextData="richTextData" :rowData="rowData" @rowView="rowView" />
    </BaseDrawer>

    <!-- 预览 -->
    <BaseDialog
      v-if="richTextVisible"
      :close-on-click-modal="true"
      :title="$t('button.viewRichText')"
      :visible.sync="richTextVisible"
      width="60%"
    >
      <ViewRichText :issueDesc="currentRichTextData" />
    </BaseDialog>
  </BaseWrap>
</template>
<script>
import moment from 'moment'
import {
  issueList,
  issueQueryRichText,
  issueEdit,
  issueDelete,
  issueChangeStatus
} from '@/api/sys/issue'
import { fileEexportIssue } from '@/api/quote/file-export'

import TableList from './components/TableList'
import PanelList from './components/PanelList'
import IssueDetail from './components/IssueDetail'
import ViewRichText from '@/widgets/ViewRichText'

export default {
  name: 'IssueNewPanel',
  components: { TableList, PanelList, IssueDetail, ViewRichText },
  data() {
    return {
      // 创建时间
      createTime: [
        moment()
          .startOf('month')
          .format('YYYY-MM-DD HH:mm:ss'),
        moment()
          .endOf('month')
          .format('YYYY-MM-DD HH:mm:ss')
      ],
      // 查询条件
      queryForm: {
        issueType: '',
        issueStatus: '',
        issueLevel: '',
        issueCreateUser: '',
        issueAppointUser: ''
      },
      // 请求
      isRequesting: false,
      // 表格数据
      tableData: [],
      // 富文本信息
      richTextData: '',
      // 当前富文本信息
      currentRichTextData: '',
      // 是否加载完毕
      loadFish: false,
      // table 模式
      modelVal: '面板模式',
      // 详情弹框是否可见
      detailVisible: false,
      // 行数据
      rowData: null,
      // 富文本预览标识
      richTextVisible: false,
      // 时间选择快捷方式
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '当前月',
            onClick(picker) {
              const start = moment()
                .startOf('month')
                .format('YYYY-MM-DD HH:mm:ss')
              const end = moment()
                .endOf('month')
                .format('YYYY-MM-DD HH:mm:ss')
              picker.$emit('pick', [start, end])
            }
          }
        ]
      }
    }
  },
  computed: {
    /** 过滤数据 */
    filterData() {
      let result = this.$deepCopy(this.tableData)
      for (const key in this.queryForm) {
        if (this.queryForm[key] || this.queryForm[key] === 0) {
          switch (key) {
            case 'issueType':
              result = result.filter(item => item.issueType === this.queryForm[key])
              break
            case 'issueStatus':
              result = result.filter(item => item.issueStatus === this.queryForm[key])
              break
            case 'issueLevel':
              result = result.filter(item => item.issueLevel === this.queryForm[key])
              break
            case 'issueCreateUser':
              result = result.filter(item => item.issueCreateUser === this.queryForm[key])
              break
            default:
              result = result.filter(item => item.issueAppointUser === this.queryForm[key])
              break
          }
        }
      }
      return result
    }
  },
  created() {
    this.pageDataInit()
    /** 问题详情查看 */
    this.$bus.$on('issue-view', item => {
      this.rowView(item)
    })
    /** 问题状态修改 */
    this.$bus.$on('issue-state-edit', item => {
      this.changeState(item)
    })
    /** 问题详情修改 */
    this.$bus.$on('issue-edit', (formData, editText) => {
      this.rowEdit(formData, editText)
    })
    /** 问题详情删除 */
    this.$bus.$on('issue-delete', item => {
      this.rowDelete(item)
    })
    /** 富文本预览标识 */
    this.$bus.$on('rich-view', richText => {
      this.richTextVisible = true
      this.currentRichTextData = richText
    })
  },
  beforeDestroy() {
    /** 问题详情查看 */
    this.$bus.$off('issue-view')
    /** 问题状态修改 */
    this.$bus.$off('issue-state-edit')
    /** 问题详情修改 */
    this.$bus.$off('issue-edit')
    /** 问题详情删除 */
    this.$bus.$off('issue-delete')
    /** 富文本预览标识 */
    this.$bus.$off('rich-view')
  },
  mounted() {
    this.$nextTick(() => (this.loadFish = true))
  },
  methods: {
    /* 页面数据初始化*/
    pageDataInit() {
      this.query()
    },
    /* 查询表格数据*/
    async query() {
      try {
        this.isRequesting = true
        const res = await issueList({
          issueCreateTimeBegin: this.createTime ? this.createTime[0] : '',
          issueCreateTimeEnd: this.createTime ? this.createTime[1] : ''
        })
        this.tableData = res.data
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = false
      }
    },

    /** 行查看 */
    async rowView(item) {
      try {
        this.isRequesting = true
        const res = await issueQueryRichText({ issueId: item.issueId }, { msgError: true })
        this.richTextData = res.data.issueDesc
        this.rowData = item
        this.detailVisible = true
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = false
      }
    },
    /** 行修改 */
    async rowEdit(formData, editText) {
      try {
        await this.$confirmBox(this.$t('button.save'), 'success')
        await issueEdit({ ...formData, issueDesc: editText }, { msgSuccess: true, msgError: true })
        this.detailVisible = false
        this.afterEdit()
      } catch (error) {
        console.log(error)
      }
    },
    /** 行删除 */
    async rowDelete(item) {
      try {
        await this.$confirmBox(this.$t('button.delete'), 'error')
        await issueDelete({ issueId: item.issueId }, { msgSuccess: true, msgError: true })
        this.detailVisible = false
        this.afterDelete()
      } catch (error) {
        console.log(error)
      }
    },
    /** 更改状态 */
    async changeState(item) {
      try {
        await issueChangeStatus(
          { issueId: item.issueId, issueStatus: item.issueStatus },
          { msgError: true }
        )
        this.query()
      } catch (error) {
        this.query()
      }
    },
    /** 更改状态 */
    afterEdit() {
      this.query()
    },
    /** 删除之后 */
    afterDelete() {
      this.query()
    },
    /** 导出 */
    async exportFile() {
      try {
        this.isRequesting = true
        const res = await fileEexportIssue(
          {
            issueCreateTimeBegin: this.createTime[0],
            issueCreateTimeEnd: this.createTime[1]
          },
          { downExcelFile: true, msgSuccess: true, msgError: true }
        )
        await this.$downFile(res)
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = false
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.button-area {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 40px;
  padding-left: 20px;
  padding-right: 10px;
  .left {
    display: flex;
    align-items: center;
    .search {
      margin-left: 10px;
    }
    .export {
      margin-left: 10px;
    }
    .el-range-editor--small.el-input__inner {
      height: 29px;
    }
  }
}

.query-area {
  height: 50px;
  display: flex;
  align-items: center;
  padding-left: 20px;
  background: rgba(208, 208, 208, 0.3);
  > div {
    margin-right: 10px;
  }
  .total {
    font-size: 15px;
    position: absolute;
    right: 14px;
    color: #636363;
  }
}

.line {
  height: 10px;
  border-bottom: 1px solid #efebeb;
}

.list-area {
  width: 100%;
  height: calc(100% - 90px);
  overflow: auto;
}

/deep/.el-form-item__label {
  font-size: 13px;
  color: #b9b9b9;
  font-weight: 550;
}
.el-form-item {
  margin-bottom: 6px;
}
</style>
